//
//  Codeable+Extension.swift
//  Social
//
//  Created by jasper on 2019/6/18.
//  Copyright © 2019 shengsheng. All rights reserved.
//

import Foundation

extension Encodable {
    var jsonString: String? {
        do {
            return try String(data: JSONEncoder().encode(self), encoding: .utf8)
        } catch {
            print(error)
            return nil
        }
    }
    
    var jsonObject: [AnyHashable: Any]? {
        do {
            return try JSONEncoder().encode(self).toJSON() as? [AnyHashable: Any]
        } catch {
            print(error)
            return nil
        }
    }
}

extension Decodable {
    static func decode(with decoder: JSONDecoder = JSONDecoder(), from data: Data) throws -> Self {
        return try decoder.decode(Self.self, from: data)
    }
    
    static func decode(from jsonObject: Any) throws -> Self {
        let data = try JSONSerialization.data(withJSONObject: jsonObject, options: JSONSerialization.WritingOptions())
        return try decode(from: data)
    }
}
